package io.lizard.cerrado.web.ssl.tomcat;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.startup.Tomcat;
import org.apache.coyote.UpgradeProtocol;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Servlet;

/**
 * 没有使用Spring Security时tomcat容器配置http到https转发
 *
 * @author xueqi
 * @date 2021-05-16
 * @see org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration
 */
@Configuration
// server.ssl.enabled = true 开启状态有效
@ConditionalOnProperty("server.ssl.enabled")
// 使用tomcat作为内置容器
@ConditionalOnClass({Servlet.class, Tomcat.class, UpgradeProtocol.class})
public class TomcatHttpToHttpsContainerFactoryConfig {
	@Value("${server.port}")
	private int httpsPort;

	@Value("${http.port}")
	private int httpPort;

	@Bean
	public TomcatServletWebServerFactory servletContainer() {
		TomcatServletWebServerFactory tomcat =
				new TomcatServletWebServerFactory() {

					@Override
					protected void postProcessContext(Context context) {
						SecurityConstraint securityConstraint = new SecurityConstraint();
						securityConstraint.setUserConstraint("CONFIDENTIAL");
						SecurityCollection collection = new SecurityCollection();
						collection.addPattern("/*");
						securityConstraint.addCollection(collection);
						context.addConstraint(securityConstraint);
					}
				};
		tomcat.addAdditionalTomcatConnectors(createHttpConnector());
		return tomcat;
	}

	// 创建http connector
	private Connector createHttpConnector() {
		Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
		connector.setScheme("http");
		connector.setSecure(false);
		connector.setPort(httpPort);
		connector.setRedirectPort(httpsPort);
		return connector;
	}
}
